package com.ccc.boot.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccc.boot.exception.BusinessException;
import com.ccc.boot.pojo.Query;
import com.ccc.boot.response.ResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * 通用业务实现
 *
 * @author superC
 * @version 0.1.0
 * @date 2022/3/24
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO> extends ServiceImpl<M, T> implements IBaseService<T> {

    protected static final Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);

    /**
     * 检查字段：ID
     */
    protected static final String ID = "id";

    @Override
    public boolean insert(T entity) {
        try {
            return super.save(entity);
        } catch (Exception e) {
            logger.error("【捕获异常-添加操作】\r\n异常记录：", e);
            throw new BusinessException(ResponseCode.DATA_ADD_FAILURE);
        }
    }

    @Override
    public boolean delete(Long id) {
        try {
            if (checkId(id)) {
                return super.removeById(id);
            } else {
                throw new BusinessException(ResponseCode.RESULT_DATA_NONE);
            }
        } catch (Exception e) {
            logger.error("【捕获异常-删除操作】\r\n异常记录：", e);
            throw new BusinessException(ResponseCode.DATA_DELETE_FAILURE);
        }
    }

    @Override
    public boolean update(T entity) {
        try {
            if (checkId(entity.getId())) {
                return super.updateById(entity);
            } else {
                throw new BusinessException(ResponseCode.DATA_UPDATE_FAILURE);
            }
        } catch (Exception e) {
            logger.error("【捕获异常-编辑操作】\r\n异常记录：", e);
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public T get(Long id) {
        T entity = super.getById(id);
        if (null == entity) {
            throw new BusinessException(ResponseCode.RESULT_DATA_NONE);
        }
        return entity;
    }

    @Override
    public IPage<?> page(Query query) {
        Page<T> page = new Page<>(query.getCurrent(), query.getSize());
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        // 全局进行模糊查询
        query.forEach((column, value) -> {
            // 非空，进行模糊查询
            if (value != null && value != "") {
                wrapper.like(column, value);
            }
        });
        return super.page(page, wrapper);
    }

    /**
     * 检查 ID 是否存在
     *
     * @param id {@code Long} ID
     * @return {@code boolean} ID 不存在则抛出异常
     */
    protected boolean checkId(Long id) {
        return checkUniqueness(ID, id);
    }

    /**
     * 检查是否存在
     *
     * @param column
     * @param value
     * @return {@link boolean}
     * @date 2022/3/31 14:05
     * @author superC
     */
    protected boolean checkUniqueness(String column, Object value) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        wrapper.eq(column, value);
        return super.count(wrapper) > 0;
    }
}